﻿namespace FluentMvc.MvcIntegration
{
    using System.Web.Mvc;

    public class TemplateEngine<TModel> where TModel : class,IModelInitializer<TModel>,new()
    {
        private readonly ModelContext<TModel> modelContext;
        public TemplateEngine()
        {
            modelContext = new ModelContext<TModel>();
            var model = new TModel();
            model.InitializeModel(modelContext);
        }

        public void SetMetadata(ModelMetadata metadata, string propertyName)
        {
            var setting = modelContext.GetSettings(propertyName);
            if (setting.Display != null)
                metadata.DisplayName = setting.Display;
            if (setting.DataType.HasValue)
                metadata.DataTypeName = setting.DataType.Value.ToString();
            if (setting.DisplayFormat != null)
                metadata.DisplayFormatString = setting.DisplayFormat;
            if (setting.EditorFormat != null)
                metadata.EditFormatString = setting.EditorFormat;
            if (setting.UIHint != null)
                metadata.TemplateHint = setting.UIHint;
            if (setting.NullText != null)
                metadata.NullDisplayText = setting.NullText;
            if (setting.EditorFormat != null)
                metadata.EditFormatString = setting.EditorFormat;
            if (setting.ShowForDisplay.HasValue)
                metadata.ShowForDisplay = setting.ShowForDisplay.Value;
            if (setting.ShowForEdit.HasValue)
                metadata.ShowForEdit = setting.ShowForEdit.Value;
            if (setting.Order.HasValue)
                metadata.Order = setting.Order.Value;
            if (setting.Watermark != null)
                metadata.Watermark = setting.Watermark;
            if (setting.HiddenInput.HasValue && setting.HiddenInput.Value)
            {
                metadata.TemplateHint = "HiddenInput";
                if (setting.HiddenInputDispayValue.HasValue && setting.HiddenInputDispayValue.Value)
                    metadata.HideSurroundingHtml = true;
            }
            foreach (var pair in setting.AdditionalMetadata)
                metadata.AdditionalValues.Add(pair.Key, pair.Value);
        }
    }
}